package org.redtroy.theater.service.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.redtroy.theater.bean.Activity;
import org.redtroy.theater.bean.Pager;
import org.redtroy.theater.bean.User;
import org.redtroy.theater.dao.hibernate.ActivityDAO;
import org.redtroy.theater.service.IActivityService;
import org.redtroy.theater.service.IUserService;
import org.redtroy.theater.service.dto.ActivityDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service("activityService")
public class ActivityService implements IActivityService {
	@Autowired
	@Qualifier("activityDAO")
	private ActivityDAO activityDAO;
	@Autowired
	@Qualifier("userService")
	private IUserService userService;

	public Activity createActivity(ActivityDTO activity) throws Exception {
		User user = userService.getUserByEmail(activity.getSponsorEmail());
		Activity a = new Activity();
		BeanUtils.copyProperties(activity, a);
		if (user != null) {
			a.setSponsor(user);
		} else {
			// automatically create a new user
		}
		return activityDAO.persist(a);
	}

	public Pager<Activity> listActivity(ActivityDTO cond) throws Exception {
		Criteria criteria = activityDAO.createCriteria();
		criteria.addOrder(Order.asc("createTime"));
		return activityDAO.retrievePageByCriteria(cond.getPageNo(),
				cond.getPageSize(), criteria);
	}

	public Activity getActivity(Integer activityId) throws Exception {
		return activityDAO.get(activityId);
	}

	public void setActivityDAO(ActivityDAO activityDAO) {
		this.activityDAO = activityDAO;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

}
